var express = require('express');
var router = express.Router();

var users = {};
/* GET home page. */
router.get('/', function(req, res, next) {
    res.locals.user = req.session.user || undefined;
    res.render('index', {
        title: 'chatRoom'
    });
});

router.get('/login', function(req, res, next) {
    res.render('login');
});
router.post('/login', (req, res, next) => {
    // res.locals.user = req.session.user || undefined;
    const {
        username,
        password
    } = req.body;
    if (users[username] && users[username].password == password) {
        req.session.user = {
            username
        };
    }
    res.redirect('/');
});
router.get('/reg', (req, res, next) => {
    res.render('reg');
});
router.post('/reg', (req, res, next) => {
    const {
        username,
        password,
        confirm
    } = req.body;
    if (username && password && password === confirm) {
        users[username] = {
            username,
            password
        };
        //req.session.user = null;
        //res.locals.user = req.session.user = {username};
    }
    res.redirect('/login');
});
router.get('/logout',function(req,res,next){
    res.locals.user = req.session.user = undefined;
    res.render('index');
});
module.exports = router;
